package br.com.viamais.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import br.com.viamais.infra.dao.BaseDAO;
import br.com.viamais.model.User;

/**
 * Class to user manager persistence. 
 * 
 * TODO: Logger
 * 
 * @author eduardo.dev
 */
public class UserDAO extends BaseDAO<User> {

	/**
	 * Serial Version ID.
	 */
	private static final long serialVersionUID = -7923690335276491013L;

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected Class<User> getClazz() {
		return User.class;
	}

	/**
	 * Method to get one user By name or password.
	 * 
	 * @param String
	 *            : user name
	 * @param String
	 *            : password.
	 * 
	 * @return User: if encounter a user in database
	 * @throws Throwable
	 *             : connections issues.
	 */
	public User getByUserNamePassword(String username, String password)
			throws Throwable {
		User user = null;
		this.beginTransaction();
		Criteria criteria = this.getSession().createCriteria(getClazz());
		if (username != null) {
			criteria.add(Restrictions.ilike("username", username,
					MatchMode.EXACT));
		}
		if (password != null) {
			criteria.add(Restrictions.like("password", password,
					MatchMode.EXACT));
		}
		user = (User) criteria.uniqueResult();
		this.commit();
		return user;
	}

	/**
	 * Get user by email.
	 * 
	 * @param String
	 *            : email.
	 * 
	 * @return User: user.
	 * @throws Throwable
	 *             : connections issues.
	 */
	public User getByEmail(String email) throws Throwable {
		User user = null;
		this.beginTransaction();
		Criteria criteria = this.getSession().createCriteria(getClazz());
		if (email != null) {
			criteria.add(Restrictions.ilike("email", email, MatchMode.EXACT));
		}
		user = (User) criteria.uniqueResult();
		this.commit();
		return user;
	}

	/**
	 * Filter do get users by name and user name.
	 * 
	 * @param String: name
	 * @param String: user name
	 * @return List<User>: list of users.
	 * 
	 * @throws Throwable: Connections problems.
	 */
	@SuppressWarnings("unchecked")
	public List<User> getByNameUsername(String name, String username)
			throws Throwable {
		List<User> users = null;
		this.beginTransaction();
		Criteria criteria = this.getSession().createCriteria(getClazz());
		if (name != null) {
			criteria.add(Restrictions.ilike("name", name, MatchMode.ANYWHERE));
		}
		if (username != null) {
			criteria.add(Restrictions.ilike("username", username,
					MatchMode.ANYWHERE));
		}
		users = criteria.list();
		this.commit();
		return users;
	}
}
